package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    /**
     * 获取用户登录名
     * @return
     */
    @RequestMapping("/getUserInfo")
    @PreAuthorize("isAuthenticated()")
    public Result getUserInfo() {

        try {
            SecurityContext context = SecurityContextHolder.getContext();
            User user = (User) context.getAuthentication().getPrincipal();
            // 获取用户名
            String username = user.getUsername();
            return  new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }

    /**
     * 分页查询所有用户
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    @PreAuthorize("isAuthenticated()")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        if (queryString != null) {
            // 条件非空时,模糊检索添加"%"
            queryString = "%" + queryString + "%";
        }

        try {
            PageResult pageResult = userService.findPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),queryString);
            return new Result(true, MessageConstant.QUERY_USERS_SUCCESS,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.QUERY_USERS_FAIL);
        }










    }

}
